import { nextTick } from 'vue'
import { defineStore } from 'pinia'

export const useAccountBookStore = defineStore('accountBook', {
  state: () => ({
    peoples: [
      '马淇',
      '何宇',
      '韦涛',
      '唐峰',
      '马永杰',
      '森森',
      '_19',
      '李老师',
      '森森朋友1',
      '_19朋友1',
      '_19朋友2',
      '_19朋友3'
    ],
    payRecords: localStorage.getItem('payRecords')
      ? JSON.parse(localStorage.getItem('payRecords'))
      : []
  }),
  getters: {
    payRecordsVO: (state) => {
      return state.payRecords.map((payRecordItem) => {
        let result = { ...payRecordItem }
        payRecordItem.peoples?.forEach((peopleItem) => {
          result[peopleItem] = toFixed(payRecordItem.payNum / payRecordItem.peoples.length)
        })
        return result
      })
    },
    totalPayable(state) {
      let payableMap = {}
      let receivableMap = {}
      state.peoples.forEach((peopleItem) => {
        payableMap[peopleItem] = 0
        receivableMap[peopleItem] = 0
      })
      this.payRecordsVO.forEach((payRecordItem) => {
        state.peoples.forEach((peopleItem) => {
          payableMap[peopleItem] += payRecordItem[peopleItem] || 0
          if (peopleItem === payRecordItem.payPeople) {
            receivableMap[peopleItem] += payRecordItem.payNum || 0
          }
        })
      })
      let result = Object.keys(payableMap).map((item) => {
        return {
          people: item,
          payable: toFixed(payableMap[item]),
          receivable: toFixed(receivableMap[item]),
          realPayable: toFixed(payableMap[item] - receivableMap[item])
        }
      })
      // console.log(result)
      return result
    },
    settlementList() {
      let result = []
      let payableList = this.totalPayable
        .filter((item) => item.realPayable > 0)
        .map((item) => {
          return {
            people: item.people,
            value: item.realPayable
          }
        })
      let receivableList = this.totalPayable
        .filter((item) => item.realPayable < 0)
        .map((item) => {
          return {
            people: item.people,
            value: -item.realPayable
          }
        })
      while (payableList.length > 0 && receivableList.length > 0) {
        let payableMaxIndex = getMaxIndex(payableList)
        let receivableMaxIndex = getMaxIndex(receivableList)
        // console.log(receivableMaxIndex, JSON.stringify(receivableList))
        let payableMax = payableList[payableMaxIndex]
        let receivableMax = receivableList[receivableMaxIndex]
        let count = receivableMax.value - payableMax.value
        if (count > 0) {
          receivableMax.value = count
          result.push({
            payer: payableMax.people,
            payee: receivableMax.people,
            value: toFixed(payableMax.value)
          })
          payableList.splice(payableMaxIndex, 1)
        } else if (count === 0) {
          result.push({
            payer: payableMax.people,
            payee: receivableMax.people,
            value: toFixed(payableMax.value)
          })
          payableList.splice(payableMaxIndex, 1)
          receivableList.splice(receivableMaxIndex, 1)
        } else if (count < 0) {
          payableMax.value = -count
          result.push({
            payer: payableMax.people,
            payee: receivableMax.people,
            value: toFixed(receivableMax.value)
          })
          receivableList.splice(receivableMaxIndex, 1)
        }
      }
      console.log(result.reduce((a, b) => a + b.value, 0))
      return result
    }
  },
  actions: {
    addPayRecord(payRecord) {
      this.payRecords.push(JSON.parse(JSON.stringify(payRecord)))
      nextTick(() => {
        localStorage.setItem('payRecords', JSON.stringify(this.payRecords))
      })
    },
    deletePayRecord(index) {
      this.payRecords.splice(index, 1)
      nextTick(() => {
        localStorage.setItem('payRecords', JSON.stringify(this.payRecords))
      })
    },
    updatePayRecord(index, payRecord) {
      this.payRecords[index] = payRecord
      nextTick(() => {
        localStorage.setItem('payRecords', JSON.stringify(this.payRecords))
      })
    }
  }
})

// function getMax(list) {
//   let max = list[0].value
//   for (let i = 1; i < list.length; i++) {
//     if (max < list[i].value) {
//       max = list[i].value
//     }
//   }
//   return max
// }
function getMaxIndex(list) {
  let maxIndex = 0
  let max = list[maxIndex].value
  for (let i = 1; i < list.length; i++) {
    if (max < list[i].value) {
      max = list[i].value
      maxIndex = i
    }
  }
  return maxIndex
}

function toFixed(num, d = 2) {
  return Number(num.toFixed(d))
}
